<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_aikefu/model')->方法名();
*/
namespace jy_aikefu;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function payresult($order=array(),$payresult=array(),$ispay=0){
		$update=array(
			'status'=>1,
			'ispay'=>$ispay,
		);
		pdo_update('jy_aikefu_tcp',$update,array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
		return false;
	}
	public function payresult4($order=array(),$payresult=array()){
		$update=array(
			'ispay'=>1,
		);
		pdo_update('jy_aikefu_tcp',$update,array('id'=>$order['id'],'uniacid'=>$_SESSION['uniacid']));
		return false;
	}
	public function request($rurl,$post=null,$isres=false){
		$basic=$this->plugin_setting('basic');
		if(!$basic['apikey']){
			if($isres){
				$res['choices'][0]['text']='机器人暂时无法使用，请联系管理员，设置好基本参数文心API Key';
				return $res;
			}else{
				exi('机器人暂时无法使用，请联系管理员，设置好基本参数API Key','error');
			}
		}
		if(!$basic['secretkey']){
			if($isres){
				$res['choices'][0]['text']='机器人暂时无法使用，请联系管理员，设置好基本参数文心Secret Key';
				return $res;
			}else{
				exi('机器人暂时无法使用，请联系管理员，设置好基本参数文心Secret Key','error');
			}
		}
		$access_token=$this->access_token($basic);
		$rurl .='?access_token='.$access_token;
		$post=ijson_encode($post);
		$result=cfc('http')->ihttp_request($rurl,$post);
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$data=@json_decode($data,true);
		if($data['errcode']){
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			$message='访问接口错误，以下为原始数据：'.$result['content'];
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	public function access_token($basic=array()){
		$basic=$basic?:$this->plugin_setting('basic');
		if($basic['expires_in']>time() && $basic['access_token']){
			return $basic['access_token'];
		}
		if(!$basic['apikey']){
			if($isres){
				$res['choices'][0]['text']='机器人暂时无法使用，请联系管理员，设置好基本参数文心API Key';
				return $res;
			}else{
				exi('机器人暂时无法使用，请联系管理员，设置好基本参数API Key','error');
			}
		}
		if(!$basic['secretkey']){
			if($isres){
				$res['choices'][0]['text']='机器人暂时无法使用，请联系管理员，设置好基本参数文心Secret Key';
				return $res;
			}else{
				exi('机器人暂时无法使用，请联系管理员，设置好基本参数文心Secret Key','error');
			}
		}
		$url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='.$basic['apikey'].'&client_secret='.$basic['secretkey'];
		$result=cfc('http')->ihttp_request($url);
		if(is_error($result)){			
			$message="访问失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		$res=@json_decode($data,true);
		if(!$res['access_token']){
			exi('获取access_token失败！'.$res['error'].'-'.$res['error_description'],'error');
		}
		$basic['refresh_token']=$res['refresh_token'];
		$basic['expires_in']=$res['expires_in']+time();
		$basic['access_token']=$res['access_token'];
		$this->plugin_setting('basic',$basic);
		return $basic['access_token'];
	}
	//获取聊天文本
	public function getmsg($content,$isexi=false,$workerid=0){
		$worker=pdo_get('jy_aikefu_worker',array('uniacid'=>$_SESSION['uniacid'],'id'=>$workerid));
		$basic=$this->plugin_setting('basic');
		//在线
		if($worker['isonline']){
			for($i=1;$i<=5;$i++){
				if($basic['onda'.$i]){
					$msg=$this->damsg($content,$basic['onda'.$i],$worker['merchid'],$worker['id']);
					if($msg || $basic['offda'.$i]==4){
						break;
					}
				}
			}
		}else{
			for($i=1;$i<=5;$i++){
				if($basic['offda'.$i]){
					//file_put_contents(ROOT_D.'/1.txt',$basic['offda'.$i]."\n",FILE_APPEND);
					$msg=$this->damsg($content,$basic['offda'.$i],$worker['merchid'],$worker['id']);
					if($msg || $basic['offda'.$i]==4){
						break;
					}
				}
			}
		}
		return $msg;
	}
	public function damsg($content,$da_type=0,$merchid=0,$workerid=0){
		if(!$da_type){
			$msg=$this->getwenda($content,$merchid,$workerid);
		}elseif($da_type==1){
			$msg=$this->getwenda($content);
		}elseif($da_type==2){
			if(strpos($this->setting['apis'],'0') !== false){
				//return '这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！这里是测试数据！';
				//text-davinci-003 gpt-3.5-turbo
				$url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
				/*$post=array(
					'model'=>'text-davinci-003',
					'prompt'=>$content,
					'max_tokens'=>2048,
				);*/
				$messages[]=array('role'=>'user','content'=>$content);
				$post=array(
					'messages'=>$messages,
				);
				$isres=$isexi?false:true;
				$res=$this->request($url,$post,$isres);
				//print_r($res);exit;
				if($res['error_code']){
					if(strpos($this->setting['apis'],'1') !== false){
						return $this->model('tuling')->getmsg($content,$isexi);
					}
					$res['message']=$res['error_msg']?:$res['error']['message'];
					if($isexi){
						exi('获取失败：'.$res['error_code'].','.$res['message'],'error');
					}else{
						return $this->setting['nomsg']?:'机器人暂时无法回答您的问题！请联系管理员！';
					}
				}
				//$msg=$res['choices'][0]['text'];
				$msg=$res['result'];
				if($msg){
					$this->upwenda($content,$msg,$merchid,$workerid);
				}
			}
		}elseif($da_type==3){
			if(strpos($this->setting['apis'],'1') !== false){
				$msg=$this->model('tuling')->getmsg($content,$isexi);
			}
		}
		return $msg;
	}
	public function getwenda($msg='',$merchid=0,$workerid=0){
		$params=array('title like'=>'%'.trim($msg).'%','status'=>1,'uniacid'=>$_SESSION['uniacid']);
		if($merchid){
			$params['merchid']=$merchid;
		}elseif($workerid){
			$params['workerid']=$workerid;
		}
		$wenda=pdo_get('jy_aikefu_wenda',$params,'','paixu desc,id desc');
		return $wenda['msg'];
	}
	//机器人入库
	public function upwenda($title='',$msg='',$merchid=0,$workerid=0){
		$wenda=pdo_get('jy_aikefu_wenda',array('title'=>trim($title),'uniacid'=>$_SESSION['uniacid']));
		if($wenda['id'] || !$title || !$msg){
			return false;
		}
		$data=array(
			'uniacid'=>$_SESSION['uniacid'],
			'title'=>$title,
			'msg'=>$msg,
			'merchid'=>$merchid,
			'workerid'=>$workerid,
			'status'=>1,
			'createtime'=>TIMESTAMP
		);
		pdo_insert('jy_aikefu_wenda',$data);
		return true;
	}
}
?>